package cn.hallele.leinsteining.ms.infrastructure.plugin.safety.encryptor;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import org.jasypt.encryption.StringEncryptor;

import java.util.Base64;
import java.util.Optional;

/**
 * 程序yml配置文件加解密类，使用ENC(密文)会被解密
 * key生成：Base64.getEncoder().encodeToString(SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded())
 *
 * @author anle5
 * @since 2024/7/28 14:46
 */
public class AESEncryptor implements StringEncryptor {
    private final static String KEY_NAME = "Encryptor.key";

    private final static String DEFAULT_KEY = "QPjL9V1wlrDrOsqJXDVBdg==";

    /**
     * aes加解密
     */
    private final AES aes;

    public AESEncryptor() {
        // 从环境变量中取key值
        this.aes = SecureUtil.aes(Base64.getDecoder()
                .decode(Optional.ofNullable(System.getenv(KEY_NAME)).orElse(DEFAULT_KEY))
        );
    }

    /**
     * Encrypt the input message
     *
     * @param message the message to be encrypted
     * @return the result of encryption
     */
    @Override
    public String encrypt(String message) {
        return aes.encryptHex(message);
    }

    /**
     * Decrypt an encrypted message
     *
     * @param encryptedMessage the encrypted message to be decrypted
     * @return the result of decryption
     */
    @Override
    public String decrypt(String encryptedMessage) {
        return aes.decryptStr(encryptedMessage);
    }
}